using System;
using System.Collections;
using System.Globalization;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace EnhancedCQWP.EnhancedContentQuery
{
    public class DdwRuntime
    {
        internal static Hashtable cultureInfoTable = new Hashtable();

        private DateTime GetDateTime(string theDate)
        {
            try
            {
                return DateTime.Parse(theDate, CultureInfo.InvariantCulture).ToUniversalTime().ToLocalTime();
            }
            catch (FormatException)
            {
                return DateTime.Parse(theDate).ToUniversalTime().ToLocalTime();
            }
        }

        public string FormatDateTime(string stringDate, long lcid, string formatString)
        {
            try
            {
                DateTime dateTime = this.GetDateTime(stringDate);
                if (formatString.Length != 0)
                {
                    CultureInfo provider = (CultureInfo)cultureInfoTable[lcid];
                    if (provider == null)
                    {
                        provider = new CultureInfo((int)lcid);
                        cultureInfoTable[lcid] = provider;
                    }
                    return dateTime.ToString(formatString, provider);
                }
                return string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public string FormatDateTimeUsingCurrentContext(string stringDate)
        {
            try
            {
                return SPUtility.FormatDate(SPContext.Current.Web, this.GetDateTime(stringDate), SPDateFormat.DateTime);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public string FormatDateUsingCurrentContext(string stringDate)
        {
            try
            {
                return SPUtility.FormatDate(SPContext.Current.Web, this.GetDateTime(stringDate), SPDateFormat.DateOnly);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public string Today()
        {
            return DateTime.Now.ToString("G", CultureInfo.InvariantCulture);
        }

        public string TodayIso()
        {
            return SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.UtcNow);
        }

        public string UrlEncode(string stringToEncode)
        {
            return HttpUtility.UrlEncode(stringToEncode);
        }

        public string Limit(string inputText, int maxLength, string additionalText)
        {
            if (inputText.Length <= maxLength)
            {
                return inputText;
            }
            return (inputText.Substring(0, maxLength) + additionalText);
        }
    }
}